<!-- <template>
  <div class="chat-container">
    <div class="chat-header">智能医诊助手</div>
    <button class="close-button" @click="$emit('close')">×</button>
    <div class="chat-body" ref="chatBody">
      <div
        v-for="(message, index) in messages"
        :key="index"
        :class="['message', message.type]"
      >
        {{ message.text }}
      </div>
    </div>
    <div class="chat-footer">
      <input
        type="text"
        v-model="userInput"
        placeholder="请输入消息..."
        @keyup.enter="handleEnter"
        :disabled="loading"
      />
      <button @click="sendMessage" :disabled="loading">
        {{ loading ? "发送中..." : "发送" }}
      </button>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick } from "vue";
import { getChatList } from "@/api/ai/chat";

export default {
  name: "ChatApp",
  setup() {
    const userInput = ref("");
    const messages = ref([]);
    const chatBody = ref(null);
    const loading = ref(false);

    const scrollToBottom = () => {
      if (chatBody.value) {
        chatBody.value.scrollTop = chatBody.value.scrollHeight;
      }
    };

    async function sendMessage() {
      if (loading.value || !userInput.value.trim()) return;

      const input = userInput.value.trim();
      messages.value.push({ text: input, type: "user-message" });
      userInput.value = "";

      // 添加加载状态消息
      messages.value.push({ text: "正在思考...", type: "pending-message" });
      await nextTick();
      scrollToBottom();

      loading.value = true;
      try {
        const result = await getChatList({ message: input });
        console.log("请求成功:", result);
        const aiResponse = result.response;
        console.log("AI的回复:", aiResponse);

        // 替换加载状态消息
        const index = messages.value.findIndex(
          (msg) => msg.type === "pending-message"
        );
        if (index !== -1) {
          messages.value.splice(index, 1, {
            text: aiResponse,
            type: "ai-message",
          });
        }
      } catch (error) {
        console.error("请求失败:", error);
        const index = messages.value.findIndex(
          (msg) => msg.type === "pending-message"
        );
        if (index !== -1) messages.value.splice(index, 1);
        messages.value.push({
          text: "请求失败，请稍后再试",
          type: "ai-message",
        });
      } finally {
        loading.value = false;
        await nextTick();
        scrollToBottom();
      }
    }

    function handleEnter(e) {
      if (!e.shiftKey && !loading.value) sendMessage();
    }

    onMounted(scrollToBottom);

    return { userInput, messages, chatBody, loading, sendMessage, handleEnter };
  },
};
</script>

<style scoped>
.pending-message {
  color: #666;
  font-style: italic;
}

.chat-container {
  width: 100%;
  height: 100%;
  max-width: 680px;
  margin: 20px auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.chat-header {
  background-color: #007bff;
  color: #fff;
  padding: 10px;
  text-align: center;
  font-size: 20px;
  font-weight: bold;
}

.chat-body {
  padding: 10px;
  height: 650px;
  overflow-y: auto;
}

.message {
  margin-bottom: 10px;
}

.user-message {
  text-align: right;
  color: #333;
}

.ai-message {
  text-align: left;
  color: #007bff;
}

.chat-footer {
  display: flex;
  align-items: center;
  padding: 10px;
  border-top: 1px solid #ddd;
}

.chat-footer input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  margin-right: 10px;
}

.chat-footer button {
  padding: 10px 20px;
  background-color: #007bff;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}

.chat-footer button:hover {
  background-color: #0056b3;
}

.close-button {
  position: absolute;
  top: 25px;
  right: 20px;
  background: none;
  border: none;
  font-size: 30px;
  cursor: pointer;
  color: #fff;
}
</style> -->

<template>
  <div class="chat-container">
    <div class="chat-header">智能医诊助手</div>
    <button class="close-button" @click="$emit('close')">×</button>
    <div class="messages" ref="messagesContainer">
      <div
        v-for="(msg, index) in messages"
        :key="index"
        :class="['message', msg.role]"
      >
        <div class="role">{{ msg.role === 'user' ? '我' : '小智' }}</div>
        <div class="content">{{ msg.content }}</div>
      </div>
    </div>

    <div class="input-area">
      <input
        v-model="inputText"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
      />
      <button @click="sendMessage" :disabled="loading">
        {{ loading ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, nextTick, onMounted } from 'vue'

const messages = ref([
  { role: 'assistant', content: '你好！我是智能医诊助手:小智，有什么可以帮您？' }
])
const inputText = ref('')
const loading = ref(false)
const messagesContainer = ref(null) // 新增消息容器引用

// 滚动到底部方法
const scrollToBottom = () => {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
  }
}

// 初始化时滚动到底部
onMounted(() => {
  nextTick(scrollToBottom)
})

async function sendMessage() {
  if (!inputText.value.trim() || loading.value) return

  try {
    loading.value = true
    const userMessage = inputText.value
    
    // 添加用户消息并滚动
    messages.value.push({ role: 'user', content: userMessage })
    inputText.value = ''
    await nextTick()
    scrollToBottom()

    const response = await fetch(
      'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions',
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          Authorization: 'sk-e4b9b757dfa347b1a83b9a4b9a767e3d' // 请替换为你的有效API密钥
        },
        body: JSON.stringify({
          model: 'qwen-plus',
          messages: [
            { role: 'system', content: '你是一个智能医诊助手，你叫小智' },
            ...messages.value.slice(1),
            { role: 'user', content: userMessage }
          ],
          stream: true
        })
      }
    )

    if (!response.ok) {
      throw new Error(await response.text())
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let fullText = ''
    
    // 创建助理消息并立即滚动
    messages.value.push({ role: 'assistant', content: fullText })
    await nextTick()
    scrollToBottom()

    while (true) {
      const { done, value } = await reader.read()
      if (done) break

      const chunk = decoder.decode(value)
      const lines = chunk.split('\n').filter(line => line.trim())

      for (const line of lines) {
        try {
          const jsonStr = line.replace(/^data: /, '')
          if (jsonStr === '[DONE]') break

          const data = JSON.parse(jsonStr)
          const delta = data.choices[0].delta.content || ''
          fullText += delta

          // 更新消息内容并滚动
          messages.value[messages.value.length - 1].content = fullText
          await nextTick()
          scrollToBottom()
        } catch (e) {
          console.error('解析错误:', e)
        }
      }
    }
  } catch (error) {
    console.error('请求失败:', error)
    messages.value.push({
      role: 'assistant',
      content: '出错了，请稍后再试：' + error.message
    })
    await nextTick()
    scrollToBottom()
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.messages {
  height: 600px;
  overflow-y: auto;
  margin-bottom: 20px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
}

.message {
  margin: 10px 0;
  padding: 8px;
  border-radius: 4px;
}

.message.user {
  background: #e3f2fd;
  margin-left: 20%;
}

.message.assistant {
  background: #fff;
  margin-right: 20%;
}

.role {
  font-weight: bold;
  color: #666;
  font-size: 0.8em;
  margin-bottom: 4px;
}

.input-area {
  display: flex;
  gap: 10px;
}

input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

button {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:disabled {
  background: #ccc;
  cursor: not-allowed;
}


.close-button {
  position: absolute;
  top: 25px;
  right: 20px;
  background: none;
  border: none;
  font-size: 30px;
  cursor: pointer;
  color: #fa3737;
}
</style>
